package com.learn.algorithm_876;

import com.dataconsruct.ListNode;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * 876. 链表的中间结点
 * https://leetcode-cn.com/problems/middle-of-the-linked-list/
 * @author gatts, 2022/1/13 15:16
 */
public class MiddleOfListNode {

    @Test
    public void test() {
        ListNode root = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        System.out.println(root);
        ListNode middleNode = middleNode(root);
        System.out.println(middleNode);
    }

    public ListNode middleNode(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode current = head;
        int count = 0;
        Map<Integer, ListNode> map = new HashMap<>();

        while (current != null) {
            map.put(count, current);
            current = current.next;
            count++;
        }

        int middle = map.size() / 2;
        return map.get(middle);
    }

}
